package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dao.DishDao;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.function.Consumer;

@Service
public class DishServiceImpl extends ServiceImpl<DishDao, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Override
    @Transactional
    public void addDishAndFlavor(DishDto dishDto) {
        super.save(dishDto);
        Long dishid = dishDto.getId();  //获取菜品的id

        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishid));

        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 查询两张不同的表，然后统一用dishDto去接查询出来的属性
     *
     * */
    @Override
    public DishDto selectDishAndFlavorById(Long id) {
        //1、查询菜品的基本信息
        Dish dish = super.getById(id);

        //拷贝dish中的普通属性属性
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);

        //2、查询当前菜品对应的口味信息
        LambdaQueryWrapper<DishFlavor> flavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        flavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(flavorLambdaQueryWrapper);
        //口味属性单独设置
        dishDto.setFlavors(flavors);
        return dishDto;
    }


    /**
     * 先更新dish表中基础字段，再对口味表中的数据进行删除再添加
     *
     * */
    @Override
    @Transactional
    public void updateDishAndFlavor(DishDto dishDto) {
        //更新dish表
        super.updateById(dishDto);

        //口味表删除，再添加
        LambdaQueryWrapper<DishFlavor> flavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        flavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(flavorLambdaQueryWrapper);

        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(new Consumer<DishFlavor>() {
            @Override
            public void accept(DishFlavor dishFlavor) {
                dishFlavor.setDishId(dishDto.getId());
            }
        });
        dishFlavorService.saveBatch(flavors);
    }
}
